var url = require('url')
var querystring = require('querystring')
var superagent = require('superagent')

var loggerOG = function (options) {
  if (!options) options = {}
  if (options instanceof superagent.Request) {
    return attachSuperagentLogger({}, options)
  }
  return attachSuperagentLogger.bind(null, options)
}

function attachSuperagentLogger (options, req) {
  var start = new Date().getTime()
  var timestamp = new Date().toLocaleString()
  var format = function (bytes) {
    return (bytes / 1024 / 1024).toFixed(2) + 'MB'
  }
  var uri = url.parse(req.url)
  var method = req.method

  var logger = global.logger

  if (options.outgoing) {
    logger.info('%s %s %s %s %s',
      !options.timestamp ? '[' + timestamp + ']' : '',
      "- ServiceRequest - {'TraceId':'" + options.traceId + "'}",
      '-' + method.toUpperCase() + '-',
      uri.href + (req.qs ? '' : '?' + querystring.encode(req.qs)),
      '(pending)'
    )
  }
  // heapUsed:'+ util.inspect(process.memoryUsage() +'
  req.on('response', function (res) {
    var mem = process.memoryUsage()
    var now = new Date().getTime()
    var elapsed = now - start
    logger.info('%s %s %s %s %s %s %s',
      !options.timestamp ? '[' + timestamp + ']' : '',
      "- ServiceRequest - {'TraceId':'" + options.traceId + "'",
      "'Url':'" + uri.href + (req.qs ? '' : '?' + querystring.encode(req.qs)) + "',",
      "'Method':'" + method.toUpperCase() + "',",
      "'Status':'" + res.status + "',",
      JSON.stringify(req._data) ? "'Params':'" + JSON.stringify(req._data).substring(0, 1000) + "'," : '',
      "'ResponseBody':'" + res.text + "'}",
      '(end in ' + elapsed + 'ms)', "'Process: heapTotal ':'" + format(mem.heapTotal) + ",'heapUsed':'" + format(mem.heapUsed) + ",'rss ':'" + format(mem.rss)
    )
  })
}

module.exports = loggerOG
